package net.chengp.esload4j.config;

import java.io.IOException;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author chengp
 * @email E-mail:chengp@chengp.net
 * @version 创建时间：2020年9月12日 下午3:21:45 
 *
 */
@Configuration
@Slf4j
public class ElasticSearchConfig implements FactoryBean<RestHighLevelClient>, InitializingBean, DisposableBean {

	@Autowired
	private ESConfig ESConfig;

	private RestHighLevelClient restHighLevelClient;

	@Override
	public void destroy() throws Exception {
		try {
			if (restHighLevelClient != null) {
				restHighLevelClient.close();
			}
		} catch (IOException e) {
			log.error("Error closing Elasticsearch restClient: ", e);
		}

	}

	@Override
	public RestHighLevelClient getObject() throws Exception {
		return restHighLevelClient;
	}

	@Override
	public Class<RestHighLevelClient> getObjectType() {
		return RestHighLevelClient.class;
	}

	@Override
	public boolean isSingleton() {
		return false;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		buildClient();
	}

	private void buildClient() {
		BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
		if (ESConfig.getUsername() != null && ESConfig.getPassword() != null) {
			credentialsProvider.setCredentials(AuthScope.ANY,
					new UsernamePasswordCredentials(ESConfig.getUsername(), ESConfig.getPassword()));
		}
		// 支持集群模式
		String[] splitHosts = ESConfig.getHost().split(",");
		HttpHost[] hosts = new HttpHost[splitHosts.length];
		for (int i = 0; i < splitHosts.length; i++) {
			hosts[i] = new HttpHost(splitHosts[i], ESConfig.getPort());
		}

		RestClientBuilder builder = RestClient.builder(hosts)
				.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
					@Override
					public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
						return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
					}
				});
		restHighLevelClient = new RestHighLevelClient(builder);

	}
}
